<!-- CheckinDialog.vue - 学生端版本 -->
<template>
  <el-dialog
      :model-value="visible"
      @update:model-value="handleVisibleChange"
      :title="`${activityTitle} - 打卡`"
      width="600px"
      :before-close="handleClose"
  >
    <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
      <el-form-item label="活动名称">
        <el-input :model-value="activityTitle" disabled />
      </el-form-item>

      <el-form-item label="打卡日期">
        <el-date-picker
            v-model="form.checkDate"
            type="date"
            placeholder="选择打卡日期"
            style="width: 100%"
            :disabled-date="disabledDate"
        />
      </el-form-item>

      <el-form-item label="打卡时间">
        <el-time-picker
            v-model="form.checkTime"
            placeholder="选择打卡时间"
            style="width: 100%"
            format="HH:mm"
            value-format="HH:mm"
        />
      </el-form-item>

      <el-form-item label="打卡说明" prop="description">
        <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入打卡说明（如：完成了哪些具体工作）"
            maxlength="500"
            show-word-limit
        />
      </el-form-item>

      <el-form-item label="上传图片">
        <div class="upload-tips">最多可上传4张图片（每张不超过5MB）</div>
        <el-upload
            v-model:file-list="fileList"
            action="/api/upload/image"
            list-type="picture-card"
            :limit="4"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :headers="uploadHeaders"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          提交打卡
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue';
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { studentCheckin } from '@/api/student';

interface CheckinForm {
  checkDate: string;
  checkTime: string;
  description: string;
}

interface Props {
  visible: boolean;
  activityId: number;
  activityTitle: string;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:visible', 'success']);

const formRef = ref();
const loading = ref(false);
const fileList = ref<UploadUserFile[]>([]);

const form = reactive<CheckinForm>({
  checkDate: new Date().toISOString().split('T')[0],
  checkTime: new Date().toTimeString().split(' ')[0].substring(0, 5),
  description: ''
});

const rules = {
  description: [
    { required: true, message: '请输入打卡说明', trigger: 'blur' },
    { min: 5, message: '打卡说明至少5个字符', trigger: 'blur' }
  ]
};

// 上传请求头（包含token）
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token');
  return token ? { Authorization: `Bearer ${token}` } : {};
});

// 处理visible变化
const handleVisibleChange = (value: boolean) => {
  emit('update:visible', value);
};

// 禁用未来日期
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};

// 文件上传处理
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.warning('最多只能上传4张图片');
};

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPGOrPNG) {
    ElMessage.error('只能上传JPG/PNG格式的图片!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!');
    return false;
  }
  return true;
};

const handleSuccess: UploadProps['onSuccess'] = (response, file) => {
  if (response.success) {
    file.url = response.data.url;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error('图片上传失败');
  }
};

const handleRemove: UploadProps['onRemove'] = () => {
  // 处理文件移除
};

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false);
  resetForm();
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  fileList.value = [];
  form.checkDate = new Date().toISOString().split('T')[0];
  form.checkTime = new Date().toTimeString().split(' ')[0].substring(0, 5);
  form.description = '';
};

// 提交打卡
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;
    const userInfoStr = localStorage.getItem('userInfo');
    const userInfo = JSON.parse(userInfoStr);
    // 构建提交数据
    const submitData = {
      userId:userInfo.id,
      description: form.description,
      imageUrls: fileList.value
          .filter(file => file.url || file.response?.data?.url)
          .map(file => file.url || file.response.data.url)
    };

    // 调用学生打卡API
    const response = await studentCheckin(props.activityId, submitData);

    if (response.success) {
      ElMessage.success('打卡成功！');
      emit('success');
      handleClose();
    } else {
      ElMessage.error(response.message || '打卡失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
    console.error('打卡失败:', error);
  } finally {
    loading.value = false;
  }
};

// 监听visible变化，重置表单
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm();
  }
});
</script>

<style scoped>
.upload-tips {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
